﻿using System;
using System.Collections.Generic;
using System.Linq;
using ComicQ.Domain.Table;
using NHibernate.Linq;

namespace ComicQ.Controller
{
    public class WarrantyController
    {
        public IList<Warranty> GetAllWarranty()
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                return session.Query<Warranty>().ToList();
            }
        }

        public IList<String> GetAllWarrantyType()
        {
            return GetAllWarranty().Select(warranty => warranty.Type).ToList();
        }

        public int AddWarranty(Warranty warranty)
        {
            try
            {
                GetAllWarranty()
                    .Where(w => w.Type == warranty.Type)
                    .Select(w => w)
                    .Single();

                return 0;
            }
            catch (Exception)
            {
                using (var session = NHibernateHelper.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        session.Save(warranty);
                        transaction.Commit();
                    }
                }

                return 1;
            }
        }

        public int EditWarranty(Warranty newWarranty, String oldType)
        {
            try
            {
                var checkWarranty = GetAllWarranty()
                    .Where(w => w.Type == newWarranty.Type)
                    .Select(w => w)
                    .Single();

                if (checkWarranty.Type == oldType)
                {
                    using (var session = NHibernateHelper.OpenSession())
                    {
                        using (var transaction = session.BeginTransaction())
                        {
                            session.SaveOrUpdate(newWarranty);
                            transaction.Commit();
                        }
                    }

                    return 1;
                }

                return 0;
            }
            catch (Exception)
            {
                using (var session = NHibernateHelper.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        session.SaveOrUpdate(newWarranty);
                        transaction.Commit();
                    }
                }

                return 1;
            }
        }

        public void DeleteWarranty(Warranty warranty)
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    session.Delete(warranty);
                    transaction.Commit();
                }
            }
        }
    }
}
